package com.zrz.service;



import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.zrz.resp.WechatOpenIdResp;
import com.zrz.resp.WechatTokenResp;
import com.zrz.util.Json;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WechatService {
    private static final Logger log = LoggerFactory.getLogger(WechatService.class);
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    public static final String WX_JSCODE2SESSION = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    @Autowired
    private RestTemplate restTemplate;
    private long expireTime = 0L;
    private String accessToken;
    private boolean checked = false;


    public String getToken() {
        long currentTime = System.currentTimeMillis();
        if (currentTime < this.expireTime) {
            return this.accessToken;
        } else {
            String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", "wx4e6bcad7b788b6f8", "940471bc4de3d29e0f4d7bf47a839461");
            WechatTokenResp tokenResp = (WechatTokenResp)this.restTemplate.getForObject(url, WechatTokenResp.class, new Object[0]);
            if (StringUtils.isNotEmpty(tokenResp.getAccessToken())) {
                this.accessToken = tokenResp.getAccessToken();
                this.expireTime = currentTime + tokenResp.getExpiresIn() * 1000L;
                return this.accessToken;
            } else {
                log.error("获取微信token失败 {}", tokenResp.getMessage());
                return "";
            }
        }
    }

    public WechatOpenIdResp getOpenId(String code) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", "wx2bce5dda1296f441", "7a86dd02661afb4a8c0a115b911bfc2f", code);
        String result = (String)this.restTemplate.getForObject(url, String.class,new Object());
        WechatOpenIdResp response = (WechatOpenIdResp)Json.toObject(result, WechatOpenIdResp.class);
        if (response.getCode() != null) {
            log.error("获取微信openId失败 {}", response.getMessage());
            return null;
        } else {
            return response;
        }
    }

    public String getUserMobile(String sessionKey, String encryptedData, String iv) {
        byte[] key = Base64.getDecoder().decode(sessionKey);
        byte[] data = Base64.getDecoder().decode(encryptedData);
        byte[] salt = Base64.getDecoder().decode(iv);

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(2, new SecretKeySpec(key, "AES"), new IvParameterSpec(salt));
            byte[] result = cipher.doFinal(data);
            String value = new String(result, StandardCharsets.UTF_8);
            log.debug("获取微信手机号 {}", value);
            JsonObject jsonObject = (new JsonParser()).parse(value).getAsJsonObject();
            if (jsonObject.has("purePhoneNumber")) {
                return jsonObject.get("purePhoneNumber").getAsString();
            }
        } catch (Exception var11) {
            var11.printStackTrace();
        }

        return "";
    }

    private void checkProperties() {
        if (!this.checked) {
            this.checked = true;
        }
    }
}
